package com.iman.Confucius.web.teacher;

import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.HtmlUtils;

import com.iman.Confucius.domain.User;
import com.iman.Confucius.service.RegisterService;
import com.iman.Confucius.service.student.CourseService;
import com.iman.Confucius.service.student.QuestionService;
import com.iman.Confucius.vo.QuestionVo;
import com.iman.Confucius.web.BaseController;
import com.iman.common.Constants;
import com.iman.common.support.Page;
import com.iman.common.util.ConfigUtil;

/**
 * 互动答疑
 */
@Controller
@RequestMapping(value="/teacher/question/*")
public class EachAnswerController extends BaseController{

	@Autowired
	private QuestionService questionService;
	
	@Inject
    RegisterService	reisterService;

	@Inject 
	CourseService courseService;
	 
	private static final String INVALID_QUESTION_CONTENT = "无效问题内容, 请重新输入";

	private static final String QUIZ_PAGE_SIZE = "10";

	private static enum QUESTION_TAB {
		OFQUEST(1), OFQUESTED(2), OFHOT(3), OFQUESTALL(4);
		public int tabId = 0;
		QUESTION_TAB(int tabId) {
			this.tabId = tabId;
		}
	}

	/**
	 * 
	 *  Function:
	 *  功能说明：显示班级答疑首页
	 *	 使用说明：默认显示待回复问题列表 (所有问题)
	 *  @author  wangxiaolei  DateTime 2014年12月16日 下午2:59:44
	 *	返回类型: ModelAndView    
	 *  @param request
	 *  @param menu
	 *  @return
	 */
	@RequestMapping(value="/init")
	public ModelAndView initMyQuestion(HttpServletRequest request){
		return initOFQUEST(request, "-1", "0", QUIZ_PAGE_SIZE,"-1");
	}
	
	/**
	 * 
	 *  Function: initOFQUEST
	 *  功能说明：显示我的提问--待回复的问题
	 *	 使用说明：
	 *  @author  Lihuai  DateTime 2014年12月20日
	 *	返回类型: ModelAndView    
	 *  @param request
	 *  @param menu
	 *  @return
	 */
	@RequestMapping(value="/ofquest/{courseId}/{pageNo}/{pageSize}")
	public ModelAndView initOFQUEST(HttpServletRequest request,
			@Valid		@PathVariable	String courseId,	
			@Valid    	@PathVariable  	String	pageNo, 
			@Valid    	@PathVariable  	String	pageSize,
			String classId){
		Long paramCourseId = null;
		if("-1".equals(courseId)){
			paramCourseId = null;
		}else if(StringUtils.isNumeric(courseId)==false){
			throw new IllegalArgumentException("无效课程标识");
		}else{
			paramCourseId = Long.parseLong(courseId);
		}
		if(StringUtils.isNumeric(pageNo) == false){
			throw new IllegalArgumentException("无效分页参数");
		}
		if(StringUtils.isNumeric(pageSize) == false){
			throw new IllegalArgumentException("无效分页参数");
		}
		Long paramClassId=null;
		if(StringUtils.isBlank(classId) || "-1".equals(classId)){
			paramClassId = null;
		}else{
			paramClassId = Long.parseLong(classId.trim());
		}
		ModelAndView view = generatePagedView(request,QUESTION_TAB.OFQUEST, paramCourseId, Integer.parseInt(pageNo), Integer.parseInt(pageSize),paramClassId);
		return view;
	}
	
	/**
	 * 
	 *  Function: initOFQUESTED
	 *  功能说明： 显示已回复的问题
	 *	 使用说明：
	 *  @author  Lihuai  DateTime Dec 20, 2014-8:30:00 PM
	 *	返回类型: ModelAndView    
	 *  @param 
	 *  @return ModelAndView
	 */
	@RequestMapping(value="/ofquested/{courseId}/{pageNo}/{pageSize}")
	public ModelAndView initOFQUESTED(HttpServletRequest request,
			@Valid		@PathVariable	String courseId,	
			@Valid    	@PathVariable  	String	pageNo, 
			@Valid    	@PathVariable  	String	pageSize,
			String classId){
		if(StringUtils.isNumeric(pageNo) == false){
			throw new IllegalArgumentException("无效分页参数");
		}
		if(StringUtils.isNumeric(pageSize) == false){
			throw new IllegalArgumentException("无效分页参数");
		}
		if(StringUtils.isNumeric(pageSize) == false){
			throw new IllegalArgumentException("无效课程标识");
		}
		Long paramCourseId = Long.valueOf(courseId);
		if("-1".equals(courseId)){
			paramCourseId = null;
		}
		Long paramClassId=null;
		if(StringUtils.isBlank(classId) || "-1".equals(classId)){
			paramClassId = null;
		}else{
			paramClassId = Long.parseLong(classId.trim());
		}

		ModelAndView view = generatePagedView(request,QUESTION_TAB.OFQUESTED, paramCourseId, Integer.parseInt(pageNo), Integer.parseInt(pageSize),paramClassId);
		return view;
	}
	
	/**
	 * 
	 *  Function: OFHOT
	 *  功能说明：显示当前热门问题
	 *	 使用说明：
	 *  @author  Lihuai  DateTime Dec 20, 2014-8:30:00 PM
	 *	返回类型: ModelAndView    
	 *  @param 
	 *  @return ModelAndView
	 */
	@RequestMapping(value="/ofhot/{courseId}/{pageNo}/{pageSize}")
	public ModelAndView initOFHOT(HttpServletRequest request,
			@Valid		@PathVariable	String courseId,	
			@Valid    	@PathVariable  	String	pageNo, 
			@Valid    	@PathVariable  	String	pageSize){
		if(StringUtils.isNumeric(pageNo) == false){
			throw new IllegalArgumentException("无效分页参数");
		}
		if(StringUtils.isNumeric(pageSize) == false){
			throw new IllegalArgumentException("无效分页参数");
		}
		if(StringUtils.isNumeric(pageSize) == false){
			throw new IllegalArgumentException("无效课程标识");
		}
		Long paramCourseId = Long.valueOf(courseId);
		if("-1".equals(courseId)){
			paramCourseId = null;
		}
		ModelAndView view = generatePagedView(request,QUESTION_TAB.OFHOT, paramCourseId, Integer.parseInt(pageNo), Integer.parseInt(pageSize),null);;
		return view;
	}
	
	/**
	 * 
	 *  Function: OFHOT
	 *  功能说明：显示全部问题
	 *	 使用说明：
	 *  @author  Lihuai  DateTime Dec 20, 2014-8:30:00 PM
	 *	返回类型: ModelAndView    
	 *  @param 
	 *  @return ModelAndView
	 */
	@RequestMapping(value="/ofquestAll/{courseId}/{pageNo}/{pageSize}")
	public ModelAndView initOFALL(HttpServletRequest request,
			@Valid		@PathVariable	String courseId,	
			@Valid    	@PathVariable  	String	pageNo, 
			@Valid    	@PathVariable  	String	pageSize){
		if(StringUtils.isNumeric(pageNo) == false){
			throw new IllegalArgumentException("无效分页参数");
		}
		if(StringUtils.isNumeric(pageSize) == false){
			throw new IllegalArgumentException("无效分页参数");
		}
		if(StringUtils.isNumeric(pageSize) == false){
			throw new IllegalArgumentException("无效课程标识");
		}
		Long paramCourseId = Long.valueOf(courseId);
		if("-1".equals(courseId)){
			paramCourseId = null;
		}
		ModelAndView view = generatePagedView(request,QUESTION_TAB.OFQUESTALL, paramCourseId, Integer.parseInt(pageNo), Integer.parseInt(pageSize),null);;;
		return view;
	}
	
	/**
	 * 
	 *  Function: generatePagedView
	 *  功能说明：获取问题列表
	 *	 使用说明：
	 *  @author  Lihuai  DateTime Dec 23, 2014-2:49:05 PM
	 *	返回类型: ModelAndView    
	 *  @param courseId 若courseId 为空则返回全部课程问题列表, 否则返回特定课程问题列表
	 *  @return ModelAndView
	 */
	private ModelAndView generatePagedView(HttpServletRequest request,QUESTION_TAB tab, Long courseId, int pageNo, int pageSize,Long classId){
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("user", getCurrentUser().getLoginName());
		model.put("uid", super.getUserIdInSession(request));
		model.put("tabstatus", String.valueOf(tab.tabId));
		
		Long userId =  super.getUserIdInSession(request);
		Map<String, Integer> pageParam = new HashMap<String, Integer>();
		pageParam.put(Constants.PAGE_INDEX_KEY, pageNo);
		pageParam.put(Constants.PAGE_SIZE_KEY, pageSize);
		
		Page<QuestionVo> questionList = new Page<QuestionVo>();
		switch(tab){
			case OFHOT:
				questionList = questionService.getHotQuestionList(pageSize, courseId,userId);
				break;
			case OFQUESTED:
				questionList = questionService.getQuestionList(pageParam, null, true, courseId,userId,classId);
				break;
			case OFQUESTALL:
				questionList = questionService.getALLQuestionList(pageParam, courseId,userId);
				break;
			case OFQUEST:
			default:
				questionList = questionService.getQuestionList(pageParam, null, false, courseId,userId,classId);
		}
		model.put("pageList", questionList);
		model.put("classId", classId);
		model.put("courseList", courseService.getStudyingCourseList(userId).getData());
		if(courseId!=null){
			model.put("selectedCourseId", courseId);
		}
		ModelAndView view =null;
		view = new ModelAndView("teacher_question",model);
		putResourceSrc(view);
		return view;
	}
	
	/**
	 * 
	 *  Function: initQuestionAdd
	 *  功能说明：显示提问页面
	 *	 使用说明：
	 *  @author  Lihuai  DateTime Dec 21, 2014-9:16:25 AM
	 *	返回类型: ModelAndView    
	 *  @param 
	 *  @return ModelAndView
	 */
	@RequestMapping(value="/questionAdd")
	public ModelAndView initQuestionAdd(){
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("user", getCurrentUser().getLoginName());
		model.put("uid", getCurrentUser().getUserId());
		model.put("courseList", courseService.getStudyingCourseList(getCurrentUser().getUserId()).getData());
		ModelAndView view =null;
		view = new ModelAndView("questionadd",model);
		putResourceSrc(view);
		return view;
	}
	
	/**
	 * 
	 *  Function: postQuestion
	 *  功能说明：保存问题并将问题分发给班级所有老师
	 *	 使用说明：
	 *  @author  Lihuai  DateTime Dec 21, 2014-9:36:19 AM
	 *	返回类型: void    
	 *  @param 
	 *  @return void
	 */
	@RequestMapping(value = "/postQuestion/{courseIdParam}")
    public @ResponseBody Map<String, String> postQuestion(HttpServletRequest request, @Valid @PathVariable	String courseIdParam) {
		String reason = "保存成功";
		boolean success = false;
		try{
			String questionContent = request.getParameter("questionContent");
			if(StringUtils.isBlank( questionContent) ){
				throw new IllegalArgumentException(INVALID_QUESTION_CONTENT);
			}
			questionContent = HtmlUtils.htmlEscape(questionContent);
			Long userId = getCurrentUser().getUserId();
			Long courseId = null;
			if("-1".equals(courseIdParam) == false && StringUtils.isNumeric(courseIdParam) == false){
				throw new IllegalArgumentException("无效课程标识");
			}
			if("-1".equals(courseIdParam) == false){
				courseId = Long.valueOf(courseIdParam);
			}
			questionService.postQuestion(courseId, questionContent, questionContent, userId);
			success = true;
		}catch(IllegalArgumentException e){
			reason = e.getMessage();
		}
        Map<String,String> resultMap = new HashMap<String, String>();
        resultMap.put("success", String.valueOf(success));
        resultMap.put("reason", reason);
        System.out.println(resultMap);
        return resultMap;
    }  
	@RequestMapping(value = "/ofanwser/{quizId}")
	public ModelAndView ofAnwser(HttpServletRequest request,
			@Valid		@PathVariable	String quizId){
		User user = getCurrentUser(request);
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("user", user.getLoginName());
		model.put("uid", user.getUserId());
		String menu = request.getParameter("menu");
		if(StringUtils.isBlank(menu) == false){
			model.put("menu", menu);
		}
		String currentTab = request.getParameter("currentTab");
		if(StringUtils.isBlank(currentTab) == false ){
			model.put("currentTab", currentTab);
		}
		String selectedCourseId = request.getParameter("selectedCourseId");
		if(StringUtils.isBlank(selectedCourseId) == false){
			model.put("selectedCourseId", selectedCourseId);
		}
		if(StringUtils.isNumeric(quizId)==false){
			throw new IllegalArgumentException("无效问题标识");
		}
		QuestionVo questionObject = questionService.getQuestionDetail(Long.valueOf(quizId));
		questionService.updateQuestionViewcnt(questionObject.getQuizId());
		model.put("questionObject", questionObject);
		model.putAll(this.getConfigItems());
		ModelAndView view =null;
		view = new ModelAndView("teacher/teac_questionaans",model);
		putResourceSrc(view);
		return view;
	}
	
	private User getCurrentUser(HttpServletRequest request){
		long userId = super.getUserIdInSession(request);
		return reisterService.getUser(userId);
	}
	private Map<String, Object> getConfigItems(){
		Map<String, Object> configureItemMap = new HashMap<String, Object>();
		 String imgbasePath  =ConfigUtil.getString( "image.server" );; 
		 String cssbasePath  =ConfigUtil.getString( "css.server" );; 
		 configureItemMap.put("iconpath", imgbasePath );
		 configureItemMap.put("csspath", cssbasePath );
		return configureItemMap;
	}
	/**
	 * 
	 *  Function: getCurrentUser
	 *  功能说明：
	 *	 使用说明：
	 *  @author  Lihuai  DateTime Dec 20, 2014-8:41:14 PM
	 *	返回类型: User    
	 *  @param 
	 *  @return User
	 */
	//TODO fix it with session user
	private User getCurrentUser(){
		long userId = Constants.dumyUserId;
		return reisterService.getUser(userId);
	}
	
	
}
